/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chatWindow;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDesktopPane;
import main.ConnectionSigleton;
import utils.UtilsWindow;

/**
 *
 * @author linux
 */
public class ChatWindowFrameController {
    private static ChatWindowFrameController instance;
    private ChatWindowFrame cwFrame;
    private String userName;
    
    public static ChatWindowFrameController getInstance(){
        if(instance == null){
            instance = new ChatWindowFrameController();
        }
        return instance;
    }
    public void cleanFields(){
        cwFrame.setAllChat("");
        cwFrame.setOwnChat("");
        //cwFrame.model.removeAllElements();
    }
    
    public void sendMsg(String msg){
        String msg_post = "msg-post\n"+msg.length()+"\n"+msg+"\n\n";
        try {

            ConnectionSigleton.getInstance().writeSocket(msg_post);
        } catch (IOException ex) {
            Logger.getLogger(ChatWindowFrameController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
   public void logout(String nickname){
        String msg = "logout\n"+nickname+"\n\n";
        try {

            ConnectionSigleton.getInstance().writeSocket(msg);
            cwFrame.model.removeAllElements();
            
        } catch (IOException ex) {
            Logger.getLogger(ChatWindowFrameController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    
    public void show(JDesktopPane desktop) {
        if (cwFrame == null){
            cwFrame = new ChatWindowFrame();
            desktop.add(cwFrame);
            UtilsWindow.getCenterWindowCoordinates(desktop,cwFrame);
            cleanFields();
            cwFrame.setVisible(true);
            
        }else {
            if(cwFrame.isVisible()) {
                cwFrame.toFront();
                cwFrame.pack();
            }else {
                if(!desktop.isAncestorOf(cwFrame)){
                    desktop.add(cwFrame);
                }
                UtilsWindow.getCenterWindowCoordinates(desktop,cwFrame); 
                cleanFields();
                cwFrame.setVisible(true);
            }
        }
        
    }

    public ChatWindowFrame getCwFrame() {
        return cwFrame;
    }

    public void setCwFrame(ChatWindowFrame cwFrame) {
        this.cwFrame = cwFrame;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    
}
